﻿using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Utility
{
    public class SignalRClient
    {
        public string ConnectionId { get; set; }
        public string ClientName { get; set; }
        public bool IsConnected { get; set; }
        public string HubUrl { get; set; }
        public HubConnection HubConnection1 { get; set; }
        public IHubProxy HubProxy { get; set; }

        public SignalRClient(string clientName,string hubName,string hubUrl)
        {
            ClientName = clientName;
            HubUrl = hubUrl;
            HubConnection1 = new HubConnection(hubUrl);
            HubProxy = HubConnection1.CreateHubProxy(hubName);
            
            HubConnection1.StateChanged += (StateChange obj) =>
            {
                IsConnected =  obj.NewState== ConnectionState.Connected;
                OnStatusChanged?.Invoke(IsConnected);
            };

            HubProxy.On<string, string>("sendMessage", (msgtype, message) =>
            {
                OnMessageReceived?.Invoke(msgtype, message);
            });
        }
        public Action<string, string> OnMessageReceived;
        public Action<bool> OnStatusChanged;
        public async Task Start()
        {
            try
            {
                await HubConnection1.Start();
                ConnectionId = HubConnection1.ConnectionId;
            }
            catch (Exception ex)
            {
                Logger.Error("SignalRClientStartError", ex);
            }

        }
        public void Stop()
        {
            if(HubConnection1.State == ConnectionState.Connected)
                HubConnection1.Stop();
        }
    }
}
